package com.jshongli.myapplication.inspect;

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.DateUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.model.inspect.PatrolBean;
import com.jshongli.myapplication.model.inspect.PointBean;
import com.zhy.http.okhttp.OkHttpUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

public class CraetePatrolidActivity extends BaseActivity {

    @BindView(R.id.tv_time)
    TextView tv_time;

    @BindView(R.id.spinner)
    Spinner spinner;

    List<String> CableArray = new ArrayList();
    private ArrayAdapter<String> cable_adapter;
    private String selectcable = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_craete_patrolid;
    }

    @Override
    protected void initView() {
        super.initView();

        mToolbar.setTitle("开始巡查");
        initToolbarBack(mToolbar);


        initPD();
        //设置spinner
        initSpinner();
    }

    @Override
    protected void initData() {
        super.initData();

        Date currentDate = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = dateFormat.format(currentDate);
        tv_time.setText(currentTime);

        String cables = UtilPreferences.getString(mContext,"cable");
        if(cables!=null)
        {
            String[] array = cables.split(",");
            if(array.length>0){
                selectcable = array[0];
                for (String s : array) {
                    CableArray.add(s);
                }
            }
        }



    }

    //region initPD
    private ProgressDialog pd;

    private void initPD() {
        pd = new ProgressDialog(mContext);
        pd.setCanceledOnTouchOutside(false);
        pd.setCancelable(false);
        pd.setMessage("正在创建巡查，请稍后...");
    }
    //endregion

    //region spinner

    private void initSpinner() {
        //适配器
        cable_adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, CableArray);
        //设置样式
        cable_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(cable_adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String str = parent.getItemAtPosition(position).toString();
                selectcable = str;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
    }
    //endregion

    //region spinner
    private void StartXC()
    {
        String url = URLUtils.URLNoToken("manageAPI/bizPatrol/add");

        Map<String, String> map = new HashMap<String, String>();
        map.put("cable", selectcable);
        Gson gson = new Gson();
        final String s = gson.toJson(map);
        OkHttpUtils
                .postString()
                .url(url)
                .addHeader("Authorization", AccountManager.getToken())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(s)
                .tag(this)
                .build()
                .execute(new ResponseCallback<PatrolBean>(mContext) {

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                        pd.dismiss();
                        ToastUtils.show(mContext,"创建巡查失败，请重试");
                    }

                    @Override
                    public void onResponse(final PatrolBean response, int id) {
                        pd.dismiss();
                        if (response.code == 0) {
                            Bundle bundle = new Bundle();
                            bundle.putString("pId", String.valueOf(response.data.id));
                            bundle.putString("cable", selectcable);
                            openActivityForResult(PatrolCreateActivity.class,bundle,666);
                        } else {
                            if(response.msg != null && "请登录后再访问接口".equals(response.msg))
                            {
                                AppManager.exceptionExitToLogin(mContext, response.msg);
                            }else {
                                ToastUtils.show(mContext,"创建巡查失败，请重试");
                            }

                        }
                    }
                });
    }
    //endregion

    @OnClick({R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_submit:
                pd.show();
                if(selectcable.length()>0)
                {
                    StartXC();
                }else {
                    pd.dismiss();
                    ToastUtils.show(mContext,"无光缆中继段，无法巡查。");
                    return;
                }

                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==666){
            //处理回调相关操作
            Intent intent = new Intent();
            setResult(666, intent);
            finish();
        }
    }
}